/*	
	
	Copyright (c) 2007-2009 Ryan Christiansen
	
	This software is provided 'as-is', without any express or implied
	warranty. In no event will the authors be held liable for any damages
	arising from the use of this software.
	
	Permission is granted to anyone to use this software for any purpose,
	including commercial applications, and to alter it and redistribute it
	freely, subject to the following restrictions:
	
	1. The origin of this software must not be misrepresented; you must not
	claim that you wrote the original software. If you use this software
	in a product, an acknowledgment in the product documentation would be
	appreciated but is not required.
	
	2. Altered source versions must be plainly marked as such, and must not be
	misrepresented as being the original software.
	
	3. This notice may not be removed or altered from any source
	distribution.
	
*/
package funit.utils
{
	import flash.system.Capabilities;
	
	import funit.core.FailureSite;
	import funit.core.ResultState;
	import funit.core.TestResult;
	import funit.core.TestSuite;
	import funit.core.VersionInfo;
	
	import mx.formatters.DateFormatter;
	import mx.formatters.NumberFormatter;
	import mx.resources.ResourceManager;
	
	public class XmlResultWriter
	{
		private var _xmlResult:XML;
		
		
		/**
		 * @param result
		 */
		public function XmlResultWriter( result:TestResult )
		{
			write(result);
		}
		
		
		/**
		 * @param result
		 */
		private function write( result:TestResult ) : void
		{
			_xmlResult = <test-results />;
			
			var summaryResults:ResultSummarizer = new ResultSummarizer(result);
			
			_xmlResult["@name"] = formatTestName(summaryResults.name);
			_xmlResult["@total"] = summaryResults.resultCount.toString();
			_xmlResult["@failures"] = summaryResults.failureCount.toString();
			_xmlResult["@not-run"] = summaryResults.testsNotRun.toString();
			
			var dateFormatter:DateFormatter = new DateFormatter();
			dateFormatter.formatString = "YYYY-MM-DD";
			
			var timeFormatter:DateFormatter = new DateFormatter();
			timeFormatter.formatString = "JJ:NN:SS";
			
			_xmlResult.@date = dateFormatter.format( new Date() );
			_xmlResult.@time = timeFormatter.format( new Date() );
			
			writeEnvironment();
			writeCultureInfo();
			
			writeResult(_xmlResult, result);
		}
		
		/**
		 * 
		 */
		private function writeEnvironment() : void
		{
			var environmentXml:XML = <environment />;
			
			environmentXml["@funit-version"] = VersionInfo.version;
			environmentXml["@os-version"] = "";							// i.e. Microsoft Windows NT 5.1.2600 Service Pack 2
			environmentXml["@platform"] = Capabilities.os;				// i.e. Win32NT
			environmentXml["@cwd"] = "";								// Current Working Directory
			environmentXml["@machine-name"] = "";						// Machine Name
			environmentXml["@user"] = "";								// User Name
			environmentXml["@user-domain"] = "";						// User Domain Name
			
			_xmlResult.appendChild(environmentXml);
		}
		
		/**
		 * 
		 */
		private function writeCultureInfo() : void
		{
			var cultureXml:XML = <culture-info />;
			
			var localeChain:Array = ResourceManager.getInstance().localeChain;
			
			cultureXml["@current-culture"] = ( localeChain.length > 0 ) ? localeChain[0] : "";
			
			_xmlResult.appendChild(cultureXml);
		}
		
		/**
		 * @param output
		 * @param text
		 */
		private function writeCDATA( output:XML, text:String ) : void
		{
			output.appendChild( "<![CDATA[" + text + "]]>" );
		}
		
		/**
		 * @param output
		 * @param result
		 */
		private function writeResult( output:XML, result:TestResult ) : void
		{
			if (result.test is TestSuite)
			{
				writeSuiteResult(output, result);
			}
			else
			{
				writeCaseResult(output, result);
			}
		}
		
		/**
		 * @param output
		 * @param suiteResult
		 */
		private function writeSuiteResult( output:XML, suiteResult:TestResult ) : void
		{
			var suiteResultXml:XML = <test-suite />;
			
			suiteResultXml["@name"] = formatTestName(suiteResult.name);
			
			if (suiteResult.description != null)
			{
				suiteResultXml["@description"] = suiteResult.description;
			}
			
			var numberFormatter:NumberFormatter = new NumberFormatter();
			numberFormatter.precision = 3;
			
			suiteResultXml["@success"] = suiteResult.isSuccess.toString();
			suiteResultXml["@time"] = numberFormatter.format(suiteResult.time / 1000);
			//suiteResultXml["@asserts"] = suiteResult.assertCount.toString();
			
			//writeCategories(suiteResult);
			//writeProperties(suiteResult);
			
			if (suiteResult.isFailure && suiteResult.failureSite == FailureSite.SetUp)
			{
				var failureXml:XML = <failure />;
				
				var messageXml:XML = <message />;
				writeCDATA(messageXml, suiteResult.message);
				
				failureXml.appendChild(messageXml);
				
				if (suiteResult.stackTrace != null)
				{
					var stackTrace:XML = <stack-trace />;
					writeCDATA(stackTrace, suiteResult.stackTrace);
					
					failureXml.appendChild(stackTrace);
				}
				else
				{
					failureXml.appendChild( <stack-trace /> );
				}
				
				suiteResultXml.appendChild(failureXml);
			}
			
			var resultXml:XML = <results />;
			
			for each ( var result:TestResult in suiteResult.results )
			{
				writeResult(resultXml, result);
			}
			
			suiteResultXml.appendChild(resultXml);
			
			output.appendChild(suiteResultXml);
		}
		
		/**
		 * @param output
		 * @param caseResult
		 */
		private function writeCaseResult( output:XML, caseResult:TestResult ) : void
		{
			var caseResultXml:XML = <test-case />;
			
			caseResultXml["@name"] = formatTestName(caseResult.name);
			
			if (caseResult.description != null)
			{
				caseResultXml["@description"] = caseResult.description;
			}
			
			caseResultXml["@executed"] = caseResult.executed.toString();
			
			if (caseResult.executed)
			{
				var numberFormatter:NumberFormatter = new NumberFormatter();
				numberFormatter.precision = 3;
				
				caseResultXml["@success"] = caseResult.isSuccess.toString();
				caseResultXml["@time"] = numberFormatter.format(caseResult.time / 1000);
				//caseResultXml["@asserts"] = caseResult.assertCount.toString();
				
				//writeCategories(caseResult);
				//writeProperties(caseResult);
				
				if (caseResult.isFailure)
				{
					var failureXml:XML =
						(caseResult.resultState == ResultState.Failure) ? <failure /> : <error />;
					
					var failureMessageXml:XML = <message />;
					writeCDATA(failureMessageXml, caseResult.message);
					
					failureXml.appendChild(failureMessageXml);
					
					if (caseResult.stackTrace != null)
					{
						var stackTrace:XML = <stack-trace />;
						writeCDATA(stackTrace, caseResult.stackTrace);
						
						failureXml.appendChild(stackTrace);
					}
					else
					{
						failureXml.appendChild( <stack-trace /> );
					}
					
					caseResultXml.appendChild(failureXml);
				}
			}
			else
			{
				//writeCategories(caseResult);
				//writeProperties(caseResult);
				
				var reasonXml:XML = <reason />;
				
				var reasonMessageXml:XML = <message />;
				writeCDATA(reasonMessageXml, caseResult.message);
				
				reasonXml.appendChild(reasonMessageXml);
				
				caseResultXml.appendChild(reasonXml);
			}
			
			output.appendChild(caseResultXml);
		}
		
		/**
		 * @param name
		 * @return 
		 */
		private function formatTestName( name:String ) : String
		{
			return name.replace("::", ".");
		}
		
		
		/**
		 * 
		 */
		public function get result() : XML
		{
			return _xmlResult;
		}
		
	}
	
}
